import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:material_collection_app/utils/event_bus_util.dart';
import 'package:material_collection_app/widget/common/top_bar.dart';
import 'package:material_rfid_plugin/material_rfid_plugin.dart';
import '../utils/utils.dart';

class ScanResultPage extends StatefulWidget {
  final Map arguments;

  ScanResultPage({Key key, this.arguments}) : super(key: key);

  @override
  State<StatefulWidget> createState() => MyState();
}

class MyState extends State<ScanResultPage> {
  int id;
  List<String> rfidList = [];

  var eventBus = new EventBus();

  //TODO:模拟调试扫码成功
  bool isDebugUI = false;

  @override
  void initState() {
    super.initState();
    id = widget.arguments['id'];
    openDevice();
    if (isDebugUI) {
      rfidList.add("f01b9d43f6f8eb448419b9ac74941b47");
      rfidList.add("06fdd3fab7616018b7e28b012d0827d2");
      rfidList.add("3a4acf2ca492dc93fecbdfad29c2dbee");
      rfidList.add("bbfac92253d1907e708034880ff14f33");
      rfidList.add("4e000e93f2d8fbd1de22f519628a7acd");
      rfidList.add("929782cb36a77c77f2d60f2679681b61");
      rfidList.add("dff268d1324d3910010caaf5ba38f0ce");
      rfidList.add("11789fe16a93d054feeb73eb4cf8fb01");
    }
  }

  @override
  void dispose() {
    super.dispose();
    stopInventory();
    closeDevice();
  }

  // 打开设备
  openDevice() async {
    print('开始初始化');
    bool isInit = await MaterialRfidPlugin.init;
    String openStatus = isInit ? '设备开启成功' : '设备开启失败';

    print(openStatus);

    if (isInit) {
      // startInventoryTag();
    } else {
      Utils.showText(text: openStatus);

      if (isDebugUI) {
        //TODO:方便调试，设备开启失败也跳转到盘点结果页面
        var page = widget.arguments['page'];
        if (page == 'check_page') {
          Navigator.pushNamed(context, "/check_result", arguments: {
            'id': widget.arguments['id'],
            'itemIndex': widget.arguments['itemIndex'],
            'list': rfidList,
            'page': 'scan_results_page',
          });
        }
      } else {
        //如果是真实环境中，开启失败后就返回上一页
        Navigator.pop(context);
      }
    }
  }

  // 关闭设备
  closeDevice() async {
    bool isFree = await MaterialRfidPlugin.free;

    if (isFree) {
      print('关闭设备成功');
    } else {
      print('关闭设备失败');
    }
  }

  // 启动识别Tag循环
  startInventoryTag() async {
    bool isStart =
        await MaterialRfidPlugin.startInventoryTag(flagAnti: 0, initQ: 1);

    if (isStart) {
      print('启动识别Tag循环成功');
      readTagFromBuffer();
    } else {
      print('启动tag循环失败');
    }
  }

  // 从缓冲区读取数据
  readTagFromBuffer() async {
    List<String> data = await MaterialRfidPlugin.readTagFromBuffer;
    String uii = data[1];
    String epc = await MaterialRfidPlugin.convertUiiToEPC(uii: uii);

    if (epc != null) {
      addStringData(epc);
      stopInventory();
    }
  }

  // 停止循环识别
  stopInventory() async {
    bool data = await MaterialRfidPlugin.stopInventory;

    print('【停止循环识别】');
    print(data);
  }

  // 过滤重复数据
  void addStringData(String value) {
    bool isContains = rfidList.contains(value);

    if (!isContains) {
      //强制转换小写
      value = value.toLowerCase();

      rfidList.add(value);
    }

    setState(() {
      rfidList = rfidList;

      //直接跳转到盘点结果页
      var page = widget.arguments['page'];

      if (page == 'check_page') {
        Navigator.pushNamed(context, "/check_result", arguments: {
          'id': widget.arguments['id'],
          'itemIndex': widget.arguments['itemIndex'],
          'list': rfidList,
          'page': 'scan_results_page',
        });
      }
    });

    print("数组长度${rfidList.length}");
    print(rfidList);
  }

  @override
  Widget build(BuildContext context) {
    ScreenUtil.init(context, width: 750, height: 1334, allowFontScaling: false);

    return Scaffold(
        appBar: TopBar(
          title: '扫描结果',
        ),
        body: Container(
            color: Utils.hexToColor('#F5F6FA'),
            child: Stack(children: <Widget>[
              RawKeyboardListener(
                  focusNode: FocusNode(), // 焦点
                  autofocus: true,
                  onKey: (RawKeyEvent event) {
                    if (event.runtimeType.toString() == 'RawKeyDownEvent') {
                      RawKeyEventDataAndroid data =
                          event.data as RawKeyEventDataAndroid;
                      String _keyCode;
                      _keyCode = data.keyCode
                          .toString(); //keycode of key event (66 is return)

                      if (_keyCode == '280' ||
                          _keyCode == '293' ||
                          _keyCode == '139') {
                        startInventoryTag();
                      }
                    }
                  },
                  child: Column(
                    children: <Widget>[
                      ConstrainedBox(
                        constraints: BoxConstraints(
                          maxHeight: 0,
                        ),
                        child: new TextField(
                          showCursor: false,
                          autofocus: true,
                          decoration: InputDecoration(
                            border:
                                OutlineInputBorder(borderSide: BorderSide.none),
                          ),
                        ),
                      ),
                      Offstage(
                        offstage: rfidList.length > 0 ? true : false,
                        child: Container(
                          child: Column(
                            children: <Widget>[
                              Container(
                                margin: EdgeInsets.only(top: 50),
                                child: Image.asset(
                                  'assets/task.png',
                                  width: 319.w,
                                ),
                              ),
                              Container(
                                margin: EdgeInsets.only(top: 20),
                                child: Text('请手持扫描枪，对准盘点区域进行扫描',
                                    style: TextStyle(
                                        color: Utils.hexToColor('#888888'))),
                              )
                            ],
                          ),
                        ),
                      ),
                      Expanded(
                        child: ListView.builder(
                          itemCount: rfidList.length,
                          itemBuilder: (BuildContext context, int index) {
                            var item = rfidList[index];

                            return Container(
                              padding: EdgeInsets.symmetric(horizontal: 20.w),
                              margin: EdgeInsets.only(top: 16),
                              child: Text(item),
                            );
                          },
                        ),
                      )
                    ],
                  )),
              Offstage(
                offstage: rfidList.length > 0 ? false : true,
                child: Align(
                    alignment: Alignment.bottomCenter,
                    child: Container(
                        margin: EdgeInsets.only(bottom: 20.w),
                        child: SizedBox(
                            width: 700.w,
                            height: 110.w,
                            child: ElevatedButton(
                              onPressed: () {
                                var page = widget.arguments['page'];

                                if (page == 'check_page') {
                                  Navigator.pushNamed(context, "/check_result",
                                      arguments: {
                                        'id': widget.arguments['id'],
                                        'itemIndex':
                                            widget.arguments['itemIndex'],
                                        'list': rfidList
                                      });
                                } else if (page == 'part_out') {
                                  var nav = Navigator.of(context);
                                  nav.pop();

                                  eventBus.emit('part_scan_result',
                                      {'rfidList': rfidList});
                                  // nav.pop();
                                }
                              },
                              child: Row(
                                mainAxisAlignment: MainAxisAlignment.center,
                                children: <Widget>[
                                  Image.asset('assets/submit.png', width: 12),
                                  Container(
                                    margin: EdgeInsets.only(left: 8),
                                    child: Text(
                                      '提交',
                                      style: TextStyle(color: Colors.white),
                                    ),
                                  )
                                ],
                              ),
                              style: ElevatedButton.styleFrom(
                                  backgroundColor: Color(0xFF297CFF),
                                  shape: RoundedRectangleBorder(
                                      borderRadius: BorderRadius.all(
                                          Radius.circular(60.w)))),
                            )))),
              )
            ])));
  }
}
